package com.chengww.grab_rp.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.chengww.grab_rp.api.BaseResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
abstract class BaseViewModel : ViewModel() {
    val loading: MutableLiveData<Boolean> by lazy { MutableLiveData<Boolean>() }
    val error: MutableLiveData<String> by lazy { MutableLiveData<String>() }

    fun <V : BaseResponse> launch(
        response: MutableLiveData<V>? = null,
        block: suspend () -> V,
        afterSuccessBlock: (suspend (response: V) -> Unit)? = null
    ) {
        loading.postValue(true)
        // Must specify to the main thread, because it may be
        // a sub-coroutine of a running in a IO thread coroutine
        viewModelScope.launch(Dispatchers.Main) {
            runCatching {
                val result = withContext(Dispatchers.IO) {
                    block()
                }
                loading.postValue(false)
                if (result.isSuccess()) {
                    afterSuccessBlock?.let {
                        it(result)
                    }
                    response?.postValue(result)
                } else {
                    error.postValue(result.error)
                }
            }.exceptionOrNull()?.let {
                loading.postValue(false)
                error.postValue("网络连接失败")
            }
        }
    }

}

object EmptyViewModel : BaseViewModel()